/* -----------------
* brief
* 1. this is code gen by tools
* 2. array like [a,b,c] after each field, define the ui html tag in view,
		a for title,
		b for show or not ,
		c for element html tag , currently suppor : check、radio、select、input、textarea、upload tag
* 3. XXX
*/

package controller

import (
	"fmt"
	"github.com/chanxuehong/wechat/mchv3/corev3"
	"github.com/chanxuehong/wechat/mchv3/corev3/event"
	"saas_sys_base/common/url_const"
	"time"

	"github.com/valyala/fasthttp"
	"log"

	//. "lego_wechat/modules/wechat/models"
	//. "lego_wechat/modules/wechat/service"

	configService "saas_sys_base/modules/config/service"
)

//原来想把WxServer放在/modules/wechat目录下的，但是一些实现细节中涉及到两个文件的互相引用，所以暂时放wechat/controller里
type WxMchv3Server struct {
	//service  WechatSdkService
	appConfigService configService.AppConfigService
}

var _vcWxMchv3Server *WxMchv3Server

func init() {
	vc := new(WxMchv3Server)
	_vcWxMchv3Server = vc
	_ctrlList = append(_ctrlList, vc)

	return
}

func (vc *WxMchv3Server) CtrlInfo() string {
	return "WxCouponServer"
}

func (vc *WxMchv3Server) RoutInit() {

}


func NewWxMchv3Server(appId, mchId, serialNo, apiV3Key string, mchPriKeyText string) (srv *corev3.Server) {
	mux := corev3.NewServeMux()

	mux.DefaultEventHandleFunc(defaultMchv3EventHandler)
	mux.EventHandleFunc(event.EventType_BusiCoupon_Send, BusiCouponSendEventHandler)

	cltV3 := corev3.NewClientV3(appId, mchId, apiV3Key, serialNo, mchPriKeyText, nil )
	if cltV3 == nil {
		return nil
	}
	msgServer := corev3.NewServer(appId, mchId, apiV3Key, serialNo, cltV3, mux, nil)
	return msgServer
}

func defaultMchv3EventHandler(ctx *corev3.Context) {
	log.Printf("收到事件:\n%s\n", ctx.MixedMsg.EventType)

	//ctx.NoneResponse()
}

func BusiCouponSendEventHandler(ctx *corev3.Context) {
	log.Printf("收到事件:\n%s\n", ctx.MixedMsg.EventType)

	//ctx.NoneResponse()
}

func WxMchv3CallbackHandlerEx(ctx *fasthttp.RequestCtx) {
	fmt.Println("WxMchv3CallbackHandlerEx")
	start := time.Now()
	defer func() {
		end := time.Now()
		d := end.Sub(start)
		log.Println("duration: ", d)
		/*
		测试结果：在macbook电脑上测试
		第一次 244.3155ms （第一次要查询证书，所以耗时要多一些）
        第二次 966.6µs
		第三次：1.9967ms
		*/
	}()

	//ctxExt := &lego.RequestCtxExtent{ctx}
	var appid string
	var mchid string

	appid = ctx.UserValue(url_const.SUBPATH_APPID).(string)
	mchid = ctx.UserValue(url_const.SUBPATH_MCHID).(string)

	if appid == "" || mchid == "" {
		corev3.DefaultErrorHandler.ServeError(ctx, fmt.Errorf("mchid_v3<%s> appid<%s> must be non-nil", mchid, appid))
		return
	}
	//
	msgServer := GetMchv3ServerByAppidAndMchId(appid, mchid)
	if msgServer == nil {
		corev3.DefaultErrorHandler.ServeError(ctx, fmt.Errorf("mchid_v3<%s> appid<%s> not register in the system", mchid, appid))
		return
	}

	//校验一下appid和mchid是否正确,如果这里出错，一般是初始化那里有问题，一般不会出错，后面把这个逻辑移到只有debug版本才会检查
	//这个校验其实校验不出appid是否正确，TODO 后面需要在消息体里解析出appid，来做个对比校验
	if msgServer.AppId() != appid {
		corev3.DefaultErrorHandler.ServeError(ctx, fmt.Errorf("invalid appid<%s>, shall equal to appid<%s> in system ", appid, msgServer.AppId()))
		return
	}

	if msgServer.MchId() != mchid {
		corev3.DefaultErrorHandler.ServeError(ctx, fmt.Errorf("invalid mchid<%s>, shall equal to  appid<%s> in system ", mchid, msgServer.MchId()))
		return
	}

	msgServer.ServeHTTP(ctx) //这是产的接口，我把他从“w http.ResponseWriter, r *http.Request”变为“ctx *fasthttp.RequestCtx”
}
